import axios from "axios";
import { currentDate3 } from "@/utils/currentDate";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getCookie } from "@/utils/auth";
import Cookies from "js-cookie";
import Vue from "vue";
import router from "@/router";
// create an axios instance
const service = axios.create({
  // baseURL: '', // url = base url + request url
  // baseURL: process.env.VUE_APP_BASE_URL,
  baseURL: "", // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000, // request timeout
  withCredentials: true
});
const CHECKDATE = ["startDate", "endDate"];
// request interceptor
service.interceptors.request.use(
  config => {
    if (config.method == "get") {
      for (const key in config.params) {
        if (CHECKDATE.includes(key)) {
          config.params[key] = config.params[key]
            ? currentDate3(config.params[key])
            : "";
        }
      }
    }
    // do something before request is sent
    // config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    if (config.method == "OPTIONS") {
      return false;
    }

    // Cookies.set("RUBIKSESSIONID", 'YTJiOTY4MDctZGU0Mi00MTE0LTliYjAtOGY5ZjM2ZDY2ODIz', { domain: '10.216.36.96:7071' })

    if (store.state.user.accessToken) {
      config.headers["Authorization"] =
        "Bearer " + store.state.user.accessToken;
    }
    if (config.url.indexOf("/rest/sql") !== -1) {
      config.headers["Authorization"] = "Basic cm9vdDp0YW9zZGF0YQ==";
    }
    // if (store.getters.jwt) {
    // config.headers['Authorization'] = 'Bearer ' + store.state.user.accessToken
    // }
    // if (store.getters.tenant) {
    //   config.headers['X-SuperLink-Tenant-Auth'] = getCookie('tenant').authenticationToken
    // }
    // if (store.getters.tenant) {
    //   config.headers['X-SuperLink-Tenant-Id'] = getCookie('tenant').token
    // }
    // config.headers["Access-Control-Allow-Headers"] = "Content-Type, AUTHENTICATE "
    return config;
  },
  error => {
    // do something with request error
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  res => {
    const {
      data: { code, message, msg, status }
    } = res;
    // sql接口的成功返回
    if (status == "succ") {
      return res;
    }
    //  sql报错
    if (status == "error") {
      // Vue.prototype.$msg("暂无数据");
      return Promise.reject(res.data.desc);
    }

    if (code === 5510) {
    }
    if (code === 1000) {
      return res.data;
    }
    if (code == "0") {
      return res;
    }
    if (code == null) {
      return res;
    }
    // 部分接口 并没有 code 直接把结果返回
    if (code === undefined) {
      return res;
    }
    // 单独处理添加设备状态
    if (res.data.backgroundColor) {
      return res;
    }
    if (code != 200) {
      Vue.prototype.$msg({
        message: message || msg || "Error",
        type: "error",
        duration: 5 * 1000
      });
      // Message({
      //   message: message || 'Error',
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      return Promise.reject(message || msg || "Error");
    } else {
      return res;
    }
  },
  async error => {
    if (error.response) {
      const isJWT =
        error.response.data &&
        error.response.data.message &&
        error.response.data.message.indexOf(
          "Access token expired.JWT has expired"
        ) !== -1;
      if (isJWT) {
        Vue.prototype.$msg({
          message: error.response.data.message,
          type: "warning"
        });

        // setTimeout(async () => {
        //   await store.dispatch("user/logout");
        //   // location.reload()
        //   router.push("/login");
        // }, 1000);

        return Promise.reject(error);
      }
    }
    // 一般是系统没有启动,接口没有响应.
    if (error.message == "Network Error") {
      // Vue.prototype.$msg({
      //   message: "系统维护中,请稍后再试!",
      //   type: "error"
      // });

      return Promise.reject(error);
    }
    // 请求超时
    if (error.message.includes("timeout")) {
      // 判断请求异常信息中是否含有超时timeout字符串
      Vue.prototype.$msg({
        message: "请求超时",
        type: "error"
      });

      return Promise.reject(error); // reject这个错误信息
    }
    const { data } = JSON.parse(JSON.stringify(error)).response;

    if (Object.prototype.toString.call(data) == "[object String]") {
      const dataMsg = data.split(":").length ? data.split(":")[1] : data;
      Vue.prototype.$msg({
        message: dataMsg,
        type: "error"
      });

      return Promise.reject(error);
    }
    // if (data && data.status && data.status == 401) {
    //   Message({
    //     message: '登陆已过期,请重新登录',
    //     type: 'warning',
    //     duration: 5 * 1000
    //   })
    //   await store.dispatch('user/logout')
    //   location.reload()

    // }
    // if (data.message && data.message == "Error processing JWT.") {
    //   Vue.prototype.$msg({
    //     message: "登陆已过期,请重新登录",
    //     type: "warning"
    //   });

    //   setTimeout(async () => {
    //     await store.dispatch("user/logout");
    //     location.reload();
    //   }, 1000);
    //   return Promise.reject(error);
    // }
    // 403没有权限
    if (data && data.status && data.status == 403) {
      Vue.prototype.$msg({
        message: data.message,
        type: "error"
      });
    }
    if (
      error &&
      error.response &&
      error.response.headers["x-superlink-error"]
    ) {
      const emessage = decodeURI(
        error.response.headers["x-superlink-error"],
        "UTF-8"
      );
      Vue.prototype.$msg({
        message: emessage,
        type: "error"
      });

      // if (error.response.headers["x-superlink-error"].indexOf('Device can not be deleted if it is currently assigned') !== -1) {
      //   Message({
      //     message: '如果设备当前已分配，则无法将其删除。',
      //     type: 'error',
      //     duration: 5 * 1000
      //   })
      // }
      // if (error.response.headers["x-superlink-error"].indexOf('Unable to delete asset. One or more device assignments reference this asset.') !== -1) {
      //   Message({
      //     message: '无法删除资源。一个或多个设备分配引用了此资源。',
      //     type: 'error',
      //     duration: 5 * 1000
      //   })
      // }
    }

    // token过期 Access token expired
    if (data && data.error_description) {
      if (
        data &&
        data.error_description.indexOf("Access token expired") !== -1
      ) {
        // await store.dispatch('user/refreshToken')
        // location.reload()
        Vue.prototype.$msg({
          message: "登陆已过期,请重新登录",
          type: "warning"
        });

        setTimeout(async () => {
          await store.dispatch("user/logout");
          location.reload();
        }, 1000);
      }
      // 刷新token也过期 重新登陆
      if (
        data &&
        data.error_description.indexOf("Invalid refresh token (expired)") !== -1
      ) {
        Vue.prototype.$msg({
          message: "登陆已过期,请重新登录",
          type: "warning"
        });
        setTimeout(async () => {
          await store.dispatch("user/logout");
          location.reload();
        }, 1000);
      }
    }

    return Promise.reject(error);
  }
);

export default service;
